package com.yitiao.simple.chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;

import java.util.concurrent.ConcurrentHashMap;

@RequiredArgsConstructor
public class NettyChatServer {
    private final int port;

    private ConcurrentHashMap<Integer, Channel> map = new ConcurrentHashMap<>();


    @SneakyThrows
    private void start() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("decoder", new StringDecoder())
                                .addLast("encoder",new StringEncoder())
                                .addLast(new NettyChatServerHandler());

                        int port = ch.remoteAddress().getPort();
//                        System.out.println("client [" + port + "] join chat.");
                        map.put(port, ch.pipeline().channel());
                    }
                });
        ChannelFuture future = server.bind(port).sync();
        System.out.println("server is started...");

        future.channel().closeFuture().sync();

        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

    public static void main(String[] args) {
        new NettyChatServer(8801).start();
    }
}
